/*
 * Copyright (c) 2010-2011 Josef Hardi <josef.hardi@gmail.com>
 * Copyright (c) 2010 Piotr Zagawa <piotr.zagawa@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package id.duapuluhdua.dakidaki.loader;

import java.util.ArrayList;

import android.os.Handler;

import id.duapuluhdua.dakidaki.MainState;
import id.duapuluhdua.dakidaki.WaitDialog;
import id.duapuluhdua.dakidaki.activities.ActivityMain;
import id.duapuluhdua.dakidaki.data.common.Database;

/**
 *
 */
public abstract class Loader
{
  /** The fields */
  protected ActivityMain mParent;
  protected Database mDatabase;
  protected MainState mState;

  private Handler mHandler;
  private WaitDialog mWaitDialog;

  /**
   * @param parent
   * @param mScreen
   * @param gpsLocationStatus
   */
  public Loader(ActivityMain parent)
  {
    mParent = parent;
    mDatabase = parent.getDatabase();
    mState = parent.getMainState();

    mHandler = new Handler();
  }

  /**
   *
   * @param selectedObjectId
   * @param listObjects
   */
  protected synchronized void selectNextObject(long selectedObjectId,
      ArrayList<Long> listObjects)
  {
    boolean bSelectionDone = false;

    for (Long objectId : listObjects) {
      if (objectId == selectedObjectId) {
        continue;
      }
      if (selectObject(objectId)) {
        bSelectionDone = true;
        break;
      }
    }

    // If no object selected then pick the current object.
    if (!bSelectionDone) {
      if (selectedObjectId != -1) {
        selectObject(selectedObjectId);
      }
    }
  }

  public void loadData()
  {
    // Display wait dialog
    mWaitDialog = new WaitDialog(mParent);
    mWaitDialog.show(null);

    Thread t = new Thread()
    {
      @Override
      public void run()
      {
        loadAllItems();
        mHandler.post(mTaskLoadingFinished);
      }
    };
    t.start();
  }

  private Runnable mTaskLoadingFinished = new Runnable()
  {
    @Override
    public void run()
    {
      if (mWaitDialog != null) {
        mWaitDialog.hide();
      }
    }
  };

  /**
   *
   */
  protected abstract void loadAllItems();

  /**
   *
   * @param objectId
   * @return
   */
  protected abstract boolean selectObject(long objectId);
}
